﻿'use strict';

angular.module('ishaCrmApp')
    .controller('searchCtrl', ['$scope', '$location', 'stateSvc', function ($scope, $location, stateSvc) {

        stateSvc.setActiveMenu('Search');

        $scope.members = [];
        $scope.dataReady = false;
        $scope.fetchInProgress = false;
        $scope.noMatchesFound = false;

        $scope.searchCriteria = '';

        $scope.$watch("searchCriteria", $.debounce(500, function () {

            if ($scope.searchCriteria.length <= 2) {

                $scope.dataReady = false;
                $scope.fetchInProgress = false;
                $scope.noMatchesFound = false;
                $scope.$apply();

            } else {

                $scope.fetchInProgress = true;
                $scope.noMatchesFound = false;
                $scope.$apply();

                gapi.client.member.memberApi.getQSMatches({ client: app.CRM_CLIENT, search_str: $scope.searchCriteria }).execute(function (resp) {
                    //console.log('memberApi.getQSMatches', resp);
                    if (resp.statusCode) {
                        $scope.fetchInProgress = false;
                        switch (resp.statusCode) {
                            case 'SUCCESS':
                                {
                                    $scope.members = resp.object;
                                    $scope.dataReady = (resp.object && resp.object.length && resp.object.length > 0);
                                    $scope.noMatchesFound = !$scope.dataReady;
                                    break;
                                }
                            case 'ERROR_LOGIN_REQUIRED':
                                {
                                    stateSvc.alertError(resp.statusCode + (resp.userFriendlyMessage ? ': ' + resp.userFriendlyMessage : ''));
                                    break;
                                }
                        }
                        $scope.$apply();
                    } else {
                        stateSvc.alertError('Invalid response from Server');
                        console.log('INVALID RESPONSE', resp);
                    }
                });

            }
        }));

        
    }]);